package com.sz.callPhoneTest.call_phone_test

import android.os.Environment
import android.os.SystemClock
import android.util.Log
import java.io.File

class FileCheckThread : Thread() {
    private val TAG = "FileCheckThread"
    private var flag = true
    private var fileChanged = false
    private var originalFileArray: Array<File> = emptyArray()
    private var fileChangedCallback: FileChangedCallback? = null

    init {
        flag = true
        fileChanged = false
        originalFileArray = getFileList()
    }

    fun addFileChangedCallback(cb: FileChangedCallback) {
        fileChangedCallback = cb
    }

    fun setFlag(f: Boolean) {
        flag = f
    }

    fun isFileChanged() : Boolean{
        return fileChanged
    }

    override fun run() {
        while (flag) {
            SystemClock.sleep(500)
            Log.i(TAG, "录音文件暂时没改变")
            val recordFileArray = getFileList()
            if (recordFileArray.size != originalFileArray.size) {
                Log.i(TAG, "录音文件有改变")
                flag = false
                fileChanged = true
                fileChangedCallback?.onFileChanged(originalFileArray, recordFileArray)
                return
            }
        }
    }

    private fun getFileList() : Array<File> {
        val parent = Environment.getExternalStorageDirectory()
        var child: File

        //获取手机厂商
        if (RomUtils.isHuawei()) {
            child = File(parent, "record")
            if (!child.exists()) {
                child = File(parent, "Sounds/CallRecord")
            }
        } else if (RomUtils.isXiaomi()) {
            child = File(parent, "MIUI/sound_recorder/call_rec")
        } else if (RomUtils.isMeizu()) {
            child = File(parent, "Recorder")
        } else if (RomUtils.isOppo()) {
            child = File(parent, "Recordings/Call Recordings")
            if (!child.exists()) {
                child = File(parent, "Recordings")
            }
        } else if (RomUtils.isVivo()) {
            child = File(parent, "Record/Call")
        } else if (RomUtils.isSamsung()) {
            child = File(parent, "Sounds")
        } else {
            child = File(parent, "")
        }

        if (!child.exists() || child.listFiles() == null) {
           return emptyArray()
        }


        return child.listFiles()!!

    }

    interface FileChangedCallback {
        fun onFileChanged(originalFileArray:Array<File>, recordFileArray:Array<File>)
    }

}